package com.cqs.example.io.serial;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 *
 * 序列化破坏单例模式
 * @Author lixw
 * @Date 7/20/20 11:58 PM
 */
@Slf4j
@Data
public class SingletonSerial implements Serializable  {
    private final static long  serialVersionUID = 6844044558331513855L;
    private static final SingletonSerial instance = new SingletonSerial();

    private final long id = System.currentTimeMillis();

    private String name = "单例测试";

    public static SingletonSerial getInstance(){
        return instance;
    }


    /**
     * Read the map in using a custom routine.
     */
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        log.info("调用了SingletonSerial　readObject");
        in.defaultReadObject();
    }



    /**
     * 解决序列化破坏单例模式
     *
     * @return
     */
    private Object readResolve(){
        System.out.println("readResolve解决序列化单例被破坏");
        //不会执行readObject（）
        return instance;
    }
}
